<template>
  <div>
    <div class="top-area">
      <el-button class="dish" @click="addDish" icon="el-icon-plus"
        >新增菜品分类</el-button
      >
      <el-button class="set-meal" @click="addSetMeal" icon="el-icon-plus"
        >新增套餐分类</el-button
      >
    </div>
    <div class="table-container">
      <el-table
        :data="paginatedData"
        style="width: 100%"
        max-height="550"
        stripe
      >
        <el-table-column prop="name" label="分类名称" width="300">
        </el-table-column>
        <el-table-column prop="type" label="分类类型" width="300">
          <template slot-scope="scope">
            <span>{{ scope.row.type == 1 ? "菜品分类" : "套餐分类" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="操作时间" width="300">
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="350">
        </el-table-column>
        <el-table-column prop="operation" label="操作">
          <template slot-scope="scope">
            <el-link type="primary" @click="handleEdit(scope.$index, scope.row)"
              >修改</el-link
            >
            <el-divider direction="vertical"></el-divider>
            <el-link
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-link
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="el-pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageInfo.page"
          :page-sizes="pageSizes"
          :page-size="pageInfo.pageSize"
          :total="tableData.length"
          layout="total, sizes, prev, pager, next, jumper"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog width="700px" :title="title" :visible.sync="showDialog">
      <el-form :model="form" ref="form" label-width="120px">
        <el-form-item
          label="分类名称"
          prop="name"
          :rules="[
            { required: true, message: '请输入分类名称', trigger: 'blur' },
          ]"
        >
          <el-input v-model="form.name" placeholder="请输入分类名称"></el-input>
        </el-form-item>

        <el-form-item
          label="排序"
          prop="sort"
          :rules="[{ required: true, message: '请输入排序', trigger: 'blur' }]"
        >
          <el-input
            v-model="form.sort"
            placeholder="请输入排序"
            type="number"
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit('confirm')"
          >确定</el-button
        >
        <el-button
          v-if="title !== '修改分类'"
          type="success"
          @click="handleSubmit('save')"
          >保存并继续添加</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getClassifications, addClassifications } from "@/api/classification";
export default {
  data() {
    return {
      //弹框相关
      title: "",
      showDialog: false,
      form: {
        name: "",
        sort: "",
      },

      pageInfo: {
        page: 1,
        pageSize: 10,
      },
      pageSizes: [10, 20, 30, 40],
      tableData: [
        {
          name: "湘菜",
          type: "菜品分类",
          updateTime: "2021-07-15 20:25:23",
          sort: "1",
          operation: "编辑",
        },
        {
          name: "粤菜",
          type: "菜品分类",
          updateTime: "2021-06-02 14:27:22",
          sort: "2",
          operation: "编辑",
        },
        {
          name: "川菜",
          type: "菜品分类",
          updateTime: "2021-07-09 14:37:13",
          sort: "3",
          operation: "编辑",
        },
        {
          name: "儿童套餐",
          type: "套餐分类",
          updateTime: "2021-07-09 14:43:45",
          sort: "4",
          operation: "编辑",
        },
        {
          name: "商务套餐",
          type: "套餐分类",
          updateTime: "2021-07-09 14:39:05",
          sort: "5",
          operation: "编辑",
        },
        {
          name: "皖菜",
          type: "菜品分类",
          updateTime: "2021-07-09 14:39:15",
          sort: "6",
          operation: "编辑",
        },
        {
          name: "鲁菜",
          type: "菜品分类",
          updateTime: "2021-07-09 14:39:19",
          sort: "7",
          operation: "编辑",
        },
        {
          name: "鲁菜",
          type: "菜品分类",
          updateTime: "2021-07-09 14:39:19",
          sort: "7",
          operation: "编辑",
        },
        {
          name: "鲁菜",
          type: "菜品分类",
          updateTime: "2021-07-09 14:39:19",
          sort: "7",
          operation: "编辑",
        },
        {
          name: "鲁菜",
          type: "菜品分类",
          updateTime: "2021-07-09 14:39:19",
          sort: "7",
          operation: "编辑",
        },
        {
          name: "鲁菜",
          type: "菜品分类",
          updateTime: "2021-07-09 14:39:19",
          sort: "7",
          operation: "编辑",
        },
      ],
      matchId: "", //匹配的id
    };
  },
  created() {
    this.init();
  },
  computed: {
    paginatedData() {
      const start = (this.pageInfo.page - 1) * this.pageInfo.pageSize;
      return this.tableData.slice(start, start + this.pageInfo.pageSize);
    },
  },
  methods: {
    //页面初始数据获取
    init() {
      getClassifications(this.pageInfo).then((res) => {
        const { records, total } = res.data;
        this.tableData = records;
        this.total = total;
      });
    },
    handleCurrentChange(page) {
      this.pageInfo.page = page;
      this.init();
    },
    handleSizeChange(val) {
      this.pageSize = val; // 更新每页显示的数据条数
      this.pageInfo.page = 1; // 切换每页数据时重置到第一页
      this.init();
    },
    //新增菜品分类
    addDish() {
      this.title = "新增菜品分类";
      this.showDialog = true;
    },
    //新增套餐分类
    addSetMeal() {
      this.title = "新增套餐分类";
      this.showDialog = true;
    },

    //弹框相关
    handleClose() {
      this.showDialog = false;
      this.resetForm();
    },
    resetForm() {
      this.form.name = "";
      this.form.sort = "";
      this.$refs.form.resetFields(); // 重置表单
    },
    handleSubmit(action) {
      this.$refs.form.validate((valid) => {
        if (valid) {
          //是确定还是保存并继续
          if (action === "confirm") {
            //如果是确定--修改
            if (this.title === "修改分类") {
              this.editConfirm();
            } else {
              //确定--新增
              this.confirm();
            }
          } else if (action === "save") {
            this.saveAndContinue();
          }
        } else {
          console.log("表单验证失败!");
        }
      });
    },
    //时间格式转换
    timeFormat(timestamp) {
      const date = new Date(timestamp);

      // 获取年份、月份、日期、小时、分钟和秒
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从 0 开始
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");

      // 格式化为所需的字符串
      const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      return formattedDate;
    },
    //新增的确定按钮
    async confirm() {
      console.log("确定操作，提交数据：", this.form);
      if (this.tableData.some((item) => item.name === this.form.name)) {
        this.$message({
          type: "error",
          message: `${this.form.name}已存在，请重新输入！`,
        });
      } else {
        if (this.title === "新增菜品分类") {
          console.log("新增菜品分类的form", this.form);
          console.log("合并之后", { ...this.form, type: "1" });
          await addClassifications({ ...this.form, type: "1" });
        } else {
          await addClassifications({ ...this.form, type: "2" });
        }
        this.init();
        this.handleClose();
        this.$message.success("添加成功");
      }
    },
    //修改的确定按钮
    async editConfirm() {
      console.log("修改里面的确定操作，提交数据：", {
        name: this.form.name,
        sort: this.form.sort / 1,
        id: this.matchId,
      });
      await addClassifications({
        name: this.form.name,
        sort: this.form.sort / 1,
        id: this.matchId,
      });
      this.handleClose();
    },
    async saveAndContinue() {
      console.log("保存并继续操作，提交数据：", this.form);
      if (this.tableData.some((item) => item.name === this.form.name)) {
        this.$message({
          type: "error",
          message: `${this.form.name}已存在，请重新输入！`,
        });
      } else {
        if (this.title === "新增菜品分类") {
          await addClassifications({ ...this.form, type: "1" });
        } else {
          await addClassifications({ ...this.form, type: "2" });
        }
        this.init();
        this.resetForm();
        this.$message.success("添加成功");
      }
    },

    //表格内操作
    handleEdit(index, row) {
      console.log("修改:", index, row);
      console.log("当前tabledata", this.tableData);
      this.tableData.forEach((item) => {
        if (item.name === row.name && item.sort === row.sort) {
          this.matchId = item.id;
        }
      });
      this.title = "修改分类";
      this.form.name = row.name;
      this.form.sort = row.sort;
      this.showDialog = true;
    },
    handleDelete(index, row) {
      console.log("删除:", index, row);
      this.$confirm("此操作将永久删除该类别, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        // this.$message.success("当前分类删除成功");
        this.$message({
          type: "error",
          message: "当前分类下关联了套餐，不能删除",
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.top-area {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  height: 60px;
  margin-bottom: 15px;
  // background-color: red;

  .dish {
    width: 160px;
    height: 45px;
    font-size: 16px;
    color: #fff;
    background-color: #333;
  }
  .set-meal {
    width: 160px;
    height: 45px;
    font-size: 16px;
    color: #333;
    background-color: #ffc200;
  }
}

.table-container {
  .el-table {
    border: solid 2px #f3f4f7;
    border-radius: 2px;
  }
  .el-pagination-container {
    display: flex;
    justify-content: center; /* 水平居中 */
    margin: 15px 0 0 0; /* 上下间距 */
  }
}

.el-dialog {
  width: 700px !important;
}
</style>
